package com.sitech.ibnms.c3p.util;

import com.sitech.ibnms.c3p.domain.SysDict;
import com.sitech.ibnms.c3p.domain.SysDictItem;
import com.sitech.ibnms.c3p.mappers.SysDictMapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>Title: SysDictUtil.java</p> <p>Description:数据字典操作类</p> <p>Copyright:
 * Copyright (c) SITECH 2011</p>
 *
 * @author LJ, liujhc @date Sep 27, 2011 2:39:19 PM
 * @version V6.0
 */
public final class SysDictUtil {

    private static SysDictMapper dictMapper() {
        Assert.notNull(DaoHolder.sysDictMapper, "ApplicationContext is not initialized");
        return DaoHolder.sysDictMapper;
    }

    @Component
    public static class DaoHolder {
        private static SysDictMapper sysDictMapper;

        @Autowired
        public DaoHolder(SysDictMapper dictMapper) {
            sysDictMapper = dictMapper;
        }
    }

    private static Logger logger = LoggerFactory.getLogger(SysDictUtil.class);

    private SysDictUtil() {
    }

    private static List<SysDictItem> findSysDictItemsBySQL(String itemsSql, Map<String, String> paramsMap) {
        if (paramsMap == null) {
            paramsMap = Collections.EMPTY_MAP;
        }
        StringBuilder sqlBuilder = new StringBuilder(itemsSql);
        Pattern pattern = Pattern.compile("#[\\w]+#");
        Matcher matcher = pattern.matcher(sqlBuilder);
        int start = 0;
        while (matcher.find(start)) {
            int end = matcher.end();
            start = matcher.start();
            String param = paramsMap.get(sqlBuilder.substring(start + 1, end - 1));
            if (param == null) {
                param = "";
            } else {
                param = param.replaceAll("'", "''");
            }
            sqlBuilder.replace(start, end, param);
            sqlBuilder.insert(start, "'");
            end = start + param.length() + 1;
            sqlBuilder.insert(end, "'");
            start = end;
        }
        return dictMapper().findSysDictItemsBySQL(sqlBuilder.toString());
    }


    /**
     * 通过数据字典的CATEGORY_ID获取对应的数据字典对象<br/> SysDict dict =
     * SysDictUtil.getSysDict("100");<br/>
     *
     * @param dictId
     * @param paramsMap sql的动态参数
     * @return
     */
    public static SysDict getSysDict(String dictId, Map paramsMap) {
        SysDict dict = dictMapper().findSysDictById(dictId);
        if (dict == null) {
            logger.warn("There is no records who's id are [{}] in table tb_sys_dict_category!", dictId);
            return new SysDict();
        }
        //如果数据字典类型配置了sql，查询内容
        if (StringUtils.isNotBlank(dict.getItemsSql())) {
            try {
                dict.getItems().addAll(findSysDictItemsBySQL(dict.getItemsSql(), paramsMap));
            } catch (Exception e) {
                logger.error(String.format("数据字典{}的itemsSql执行失败！", dict), e);
            }
        } else {
            dict.getItems().addAll(dictMapper().findSysDictItemsById(dictId));
        }
        return dict;
    }

    /**
     * 通过数据字典的CATEGORY_ID获取对应的数据字典对象<br/> SysDict dict =
     * SysDictUtil.getSysDict("100");<br/>
     *
     * @param dictId
     * @return
     */
    public static SysDict getSysDict(String dictId) {
        return getSysDict(dictId, null);
    }
}
